package com.guigu.pd.dispatch.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigu.common.utils.R;
import com.guigu.pd.dispatch.common.CustomIdGenerator;
import com.guigu.pd.dispatch.entity.*;
import com.guigu.pd.dispatch.service.*;
import com.guigu.pd.serviceapi.authfeign.CoreOrgFeign;
import com.guigu.pd.serviceapi.basefeign.TransportLineFeign;
import com.guigu.pd.serviceapi.basefeign.TransportTripsFeign;
import com.guigu.pd.serviceapi.basefeign.TransportTripsTruckDriverFeign;
import com.guigu.pd.serviceapi.omsfeign.OrderFeign;
import com.guigu.pd.serviceapi.pojo.*;
import com.guigu.pd.serviceapi.workfeign.TaskTransportFeign;
import com.guigu.pd.serviceapi.workfeign.TransportOrderFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component("dispatchTask")
@Slf4j
public class DispatchTask {

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private CoreOrgFeign coreOrgFeign;


    @Autowired
    private TransportLineFeign transportLineFeign;

    @Autowired
    private TransportTripsFeign transportTripsFeign;

    @Autowired
    private TransportTripsTruckDriverFeign transportTripsTruckDriverFeign;

    @Autowired
    private TransportOrderFeign transportOrderFeign;

    @Autowired
    private TaskTransportFeign taskTransportFeign;

    //订单分类
    @Autowired
    private OrderClassifyService orderClassifyService;

    //订单分类和订单
    @Autowired
    private OrderClassifyOrderService orderClassifyOrderService;

    //缓存路线
    @Autowired
    private CacheLineService cacheLineService;

    @Autowired
    private CacheLineDetailService cacheLineDetailService;

    @Autowired
    private CacheLineUseService cacheLineUseService;
    @Autowired
    private CustomIdGenerator customIdGenerator;

    @Autowired
    private OrderClassifyAttachService orderClassifyAttachService;







    /**
     * 智能调度
     * @param businessId  机构id
     * @param params      参数
     * @param jobId       ScheduleJobEntity 定时任务表主键id
     * @param logId       ScheduleJobLogEntity 定时任务日志表主键id
     */
    public R run(String businessId, String params, String jobId, String logId){
      //  log.info("智能调度正在执行，参数为：{},{},{},{}", businessId, params, jobId, logId);

        // 快递员点击确定收货 订单状态改为已取件 生成运单表数据
        //先根据机构id 和 状态 3已揽件 获取订单表数据  此数据是该网点已揽收入库 为调度的订单数据
        //TODO 调度完后还要修改 pd_order 订单表 status 为 4已完成 和 运单表 pd_transport_order status为 2 已调度
        List<OrderEntity> orderEntities = orderFeign.getorderxxbycurrentAgencyId(businessId);

        //临时存放订单数据 下面订单分类用
        List<OrderEntity> orderEntityList = new ArrayList<>();

        List<OrderEntity> orderEntityList1 = new ArrayList<>();

        //临时存放车次车辆司机表数据
        List<OrderClassifyAttachEntity> OrderClassifyAttachlist = new ArrayList<>();

        //临时存放某一订单分类的缓存路线数据
        List<CacheLineDetailEntity> cacheLineDetailEntityList = new ArrayList<>();

        //存放不同订单分类( 起点网点id#到达网点id 作为分类依据)
        Set<String> stringSet = new HashSet<String>();

        //存放当前的分类数据
        List<OrderClassifyEntity> orderClassifyEntityList = new ArrayList<OrderClassifyEntity>();

        //获取到网点数据进行分类(根据收获网点分类)
        //先遍历出各个订单的收货网点id
        for (OrderEntity orderEntity : orderEntities) {
            //根据订单id 去 获取该订单收货网点id
            OrderLocationEntity orderLocationEntitybyorderId = orderFeign.getOrderLocationEntitybyorderId(orderEntity.getId());
            //起点网点
            String sendAgentId = orderLocationEntitybyorderId.getSendAgentId();
            //到达网点
            String receiveAgentId = orderLocationEntitybyorderId.getReceiveAgentId();
            orderEntity.setReceiveAgentId(receiveAgentId);
            stringSet.add(sendAgentId+"#"+receiveAgentId);

            orderEntityList.add(orderEntity);
            orderEntityList1.add(orderEntity);
        }

        /**
         * 订单分类
         */
        OrderClassifyEntity orderClassifyEntity = new OrderClassifyEntity();
        for (String s : stringSet) {
            String orderClassifyid = customIdGenerator.nextId(orderClassifyEntity).toString();
            orderClassifyEntity.setId(orderClassifyid);
            orderClassifyEntity.setJobId(jobId);
            orderClassifyEntity.setJobLogId(logId);
            String[] splitStr = s.split("#");
            orderClassifyEntity.setStartAgencyId(splitStr[0]);
            orderClassifyEntity.setEndAgencyId(splitStr[1]);
            orderClassifyEntity.setClassify(s);

            //记录每个订单分类中的订单数据个数
            int number = 0;
            for(int i =orderEntityList.size()-1;i>=0;i-- ){
                //判断订单的起始网点id拼接是否和订单分类相同
                String str = orderEntityList.get(i).getCurrentAgencyId()+"#"+orderEntityList.get(i).getReceiveAgentId();
                if(str.equals(s)){
                    OrderClassifyOrderEntity orderClassifyOrderEntity = new OrderClassifyOrderEntity();
                    orderClassifyOrderEntity.setId( customIdGenerator.nextId(orderClassifyOrderEntity).toString());
                    orderClassifyOrderEntity.setOrderClassifyId(orderClassifyid);
                    orderClassifyOrderEntity.setOrderId(orderEntityList.get(i).getId());

                    orderClassifyOrderService.save(orderClassifyOrderEntity);
                    //分过订单分类的订单数据从临时订单集合里删除
                    orderEntityList.remove(i);
                    number = number + 1;
                }
            }
            orderClassifyEntity.setTotal(number);
            orderClassifyEntity.setCreateDate(new Date());
            orderClassifyService.save(orderClassifyEntity);
            orderClassifyEntityList.add(orderClassifyEntity);
        }

        /**
         * 路线规划
         */
        //根据该网点的订单分类的当前网点和目的地网点 和该网点参数 安排路线
        for (OrderClassifyEntity classifyEntity : orderClassifyEntityList)  {
            //取出订单分类的依据(起点网点id#结束网点id)
            String classify = classifyEntity.getClassify();

            String[] split = classify.split("#");
            //起点网点id
            String startid = split[0];
            //结束网点id
            String endid = split[1];

            //获取起点网点的上级转运中心id
            String getpidbystartid = coreOrgFeign.getpidbyid(startid).toString();

            //获取结束网点的上级转运中心id
            String getpidbyendid = coreOrgFeign.getpidbyid(endid).toString();

            //起点网点到上级转运中心
            TransportLine transportLinelist1 = transportLineFeign.getTransportLinelistbystartAgencyId(startid,getpidbystartid);
            if(transportLinelist1==null){
                log.info(startid +"跟" +getpidbystartid + "两点间还未开辟线路");
                continue;
            }

            //根据起点网点 转运中心 id 和终点网点 转运中心id 你 去 base库 路线表去 查询数据 直达 (只有直达)
            TransportLine transportLinelist2 = transportLineFeign.getTransportLinelistbystartAgencyId(getpidbystartid,getpidbyendid);

            if(transportLinelist2==null){
                log.info(getpidbystartid +"跟" +getpidbyendid + "两转运中心间还未开辟线路");
                continue;
            }

            //终点网点到上级转运中心
            TransportLine transportLinelist3 = transportLineFeign.getTransportLinelistbystartAgencyId(getpidbyendid,endid);
            if(transportLinelist3==null){
                log.info(startid +"跟" +getpidbystartid + "两点间还未开辟线路");
                continue;
            }

            //先生成缓存路线id
            CacheLineEntity cacheLineEntity = new CacheLineEntity();
            String s1 = customIdGenerator.nextId(cacheLineEntity).toString();
            //添加缓存路线子表 起点网点到起点网点转运中心
            CacheLineDetailEntity cacheLineDetailEntity1 = new CacheLineDetailEntity();
            cacheLineDetailEntity1.setId(customIdGenerator.nextId(cacheLineDetailEntity1).toString());
            cacheLineDetailEntity1.setCacheLineId(s1);
            cacheLineDetailEntity1.setStartAgencyId(transportLinelist1.getStartAgencyId());
            cacheLineDetailEntity1.setEndAgencyId(transportLinelist1.getEndAgencyId());
            cacheLineDetailEntity1.setSort(1);
            cacheLineDetailEntity1.setTransportLineId(transportLinelist1.getId());
            cacheLineDetailEntity1.setCreateDate(new Date());

            //添加车次车辆司机订单分类关联表
            OrderClassifyAttachEntity orderClassifyAttachEntity = new OrderClassifyAttachEntity();
            orderClassifyAttachEntity.setId(customIdGenerator.nextId(orderClassifyAttachEntity).toString());
            orderClassifyAttachEntity.setOrder(1);
            orderClassifyAttachEntity.setCreateDate(new Date());
            orderClassifyAttachEntity.setOrderClassifyId(classifyEntity.getClassify());

            //通过上面的路线id找到所有的车次
            String id1 = null;
            List<TransportTrips> querytransporttripsbytransportlineid = transportTripsFeign.querytransporttripsbytransportlineid(transportLinelist1.getId());
            for (TransportTrips transportTrips : querytransporttripsbytransportlineid) {
                //获取当前时间的时
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                int i = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
                //获取当前车次的发车时间
                String departureTime1 = transportTrips.getDepartureTime();
                String[] split1 = departureTime1.split(":");
                int s = Integer.parseInt(split1[0]);
                if(i>s){
                    id1 = transportTrips.getId();
                    break;
                }
            }
            if(id1==null){
                log.info("今天的车辆已全部发出，明天才可以发出");
                continue;
            }



            //添加缓存路线子表 起点网点上级转运中心到终点网点上级转运中心
            CacheLineDetailEntity cacheLineDetailEntity2 = new CacheLineDetailEntity();
            cacheLineDetailEntity2.setId(customIdGenerator.nextId(cacheLineDetailEntity2).toString());
            cacheLineDetailEntity2.setCacheLineId(s1);
            cacheLineDetailEntity2.setStartAgencyId(transportLinelist2.getStartAgencyId());
            cacheLineDetailEntity2.setEndAgencyId(transportLinelist2.getEndAgencyId());
            cacheLineDetailEntity2.setSort(2);
            cacheLineDetailEntity2.setTransportLineId(transportLinelist3.getId());
            cacheLineDetailEntity2.setCreateDate(new Date());

            //添加车次车辆司机订单分类关联表
            OrderClassifyAttachEntity orderClassifyAttachEntity1 = new OrderClassifyAttachEntity();
            orderClassifyAttachEntity1.setId(customIdGenerator.nextId(orderClassifyAttachEntity1).toString());
            orderClassifyAttachEntity1.setOrder(2);
            orderClassifyAttachEntity1.setCreateDate(new Date());
            orderClassifyAttachEntity1.setOrderClassifyId(classifyEntity.getClassify());
            //通过上面的路线id找到所有的车次
            String id2 = null;
            List<TransportTrips> querytransporttripsbytransportlineid1 = transportTripsFeign.querytransporttripsbytransportlineid(transportLinelist2.getId());
            for (TransportTrips transportTrips : querytransporttripsbytransportlineid1) {
                //获取当前时间的时
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                int i = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
                //获取当前车次的发车时间
                String departureTime1 = transportTrips.getDepartureTime();
                String[] split1 = departureTime1.split(":");
                int s = Integer.parseInt(split1[0]);
                if(i>s){
                    id2 = transportTrips.getId();
                    break;
                }
            }
            if(id2==null){
                log.info("今天的车辆已全部发出，明天才可以发出");
                continue;
            }




            //添加缓存路线子表 终点网点上级转运中心到终点网点
            CacheLineDetailEntity cacheLineDetailEntity3 = new CacheLineDetailEntity();
            cacheLineDetailEntity3.setId(customIdGenerator.nextId(cacheLineDetailEntity3).toString());
            cacheLineDetailEntity3.setCacheLineId(s1);
            cacheLineDetailEntity3.setStartAgencyId(transportLinelist3.getStartAgencyId());
            cacheLineDetailEntity3.setEndAgencyId(transportLinelist3.getEndAgencyId());
            cacheLineDetailEntity3.setSort(3);
            cacheLineDetailEntity3.setTransportLineId(transportLinelist3.getId());
            cacheLineDetailEntity3.setCreateDate(new Date());

            //添加车次车辆司机订单分类关联表
            OrderClassifyAttachEntity orderClassifyAttachEntity2 = new OrderClassifyAttachEntity();
            orderClassifyAttachEntity2.setId(customIdGenerator.nextId(orderClassifyAttachEntity2).toString());
            orderClassifyAttachEntity2.setOrder(3);
            orderClassifyAttachEntity2.setCreateDate(new Date());
            orderClassifyAttachEntity2.setOrderClassifyId(classifyEntity.getClassify());
            //通过上面的路线id找到所有的车次
            String id3 = null;
            List<TransportTrips> querytransporttripsbytransportlineid2 = transportTripsFeign.querytransporttripsbytransportlineid(transportLinelist3.getId());
            for (TransportTrips transportTrips : querytransporttripsbytransportlineid2) {
                //获取当前时间的时
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                int i = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
                //获取当前车次的发车时间
                String departureTime1 = transportTrips.getDepartureTime();
                String[] split1 = departureTime1.split(":");
                int s = Integer.parseInt(split1[0]);
                if(i>s){
                    id3 = transportTrips.getId();
                    break;
                }
            }
            if(id3==null){
                log.info("今天的车辆已全部发出，明天才可以发出");
                continue;
            }


            //先将 临时存放车次车辆司机list清空
            OrderClassifyAttachlist.clear();

            cacheLineDetailEntityList.clear();
            //要全部有车次的话才可以添加数据  如果没有直接返回
            cacheLineDetailService.save(cacheLineDetailEntity1);
            cacheLineDetailService.save(cacheLineDetailEntity2);
            cacheLineDetailService.save(cacheLineDetailEntity3);
            cacheLineDetailEntityList.add(cacheLineDetailEntity1);
            cacheLineDetailEntityList.add(cacheLineDetailEntity2);
            cacheLineDetailEntityList.add(cacheLineDetailEntity3);

            if(id1!=null){
                //根据车次id去 pd_transport_trips_truck_driver 车次与车辆和司机关联表 查询数据
                List<TransportTripsTruckDriver> transportTripsTruckDrivers = transportTripsTruckDriverFeign.queryTransportTripsTruckDriverbytransportTripsId(id1);
                //随机生成一个随机数 根据随机数去取数据
                int random = new Random().nextInt(transportTripsTruckDrivers.size());

                orderClassifyAttachEntity.setTripsId(transportTripsTruckDrivers.get(random).getTransportTripsId());
                orderClassifyAttachEntity.setTruckId(transportTripsTruckDrivers.get(random).getTruckId());
                orderClassifyAttachEntity.setDriverId(transportTripsTruckDrivers.get(random).getUserId());

                orderClassifyAttachService.save(orderClassifyAttachEntity);
                OrderClassifyAttachlist.add(orderClassifyAttachEntity);
            }

            if(id2!=null){
                //根据车次id去 pd_transport_trips_truck_driver 车次与车辆和司机关联表 查询数据
                List<TransportTripsTruckDriver> transportTripsTruckDrivers = transportTripsTruckDriverFeign.queryTransportTripsTruckDriverbytransportTripsId(id2);
                //随机生成一个随机数 根据随机数去取数据
                int random = new Random().nextInt(transportTripsTruckDrivers.size());

                orderClassifyAttachEntity1.setTripsId(transportTripsTruckDrivers.get(random).getTransportTripsId());
                orderClassifyAttachEntity1.setTruckId(transportTripsTruckDrivers.get(random).getTruckId());
                orderClassifyAttachEntity1.setDriverId(transportTripsTruckDrivers.get(random).getUserId());

                orderClassifyAttachService.save(orderClassifyAttachEntity1);
                OrderClassifyAttachlist.add(orderClassifyAttachEntity1);
            }

            if(id3!=null){
                //根据车次id去 pd_transport_trips_truck_driver 车次与车辆和司机关联表 查询数据
                List<TransportTripsTruckDriver> transportTripsTruckDrivers = transportTripsTruckDriverFeign.queryTransportTripsTruckDriverbytransportTripsId(id2);
                //随机生成一个随机数 根据随机数去取数据
                int random = new Random().nextInt(transportTripsTruckDrivers.size());

                orderClassifyAttachEntity2.setTripsId(transportTripsTruckDrivers.get(random).getTransportTripsId());
                orderClassifyAttachEntity2.setTruckId(transportTripsTruckDrivers.get(random).getTruckId());
                orderClassifyAttachEntity2.setDriverId(transportTripsTruckDrivers.get(random).getUserId());

                orderClassifyAttachService.save(orderClassifyAttachEntity2);
                OrderClassifyAttachlist.add(orderClassifyAttachEntity2);
            }


            //添加缓存路线表
            cacheLineEntity.setId(s1);
            cacheLineEntity.setStartAgencyId(startid);
            cacheLineEntity.setEndAgencyId(endid);
            BigDecimal add = transportLinelist1.getDistance().add(transportLinelist2.getDistance().add(transportLinelist3.getDistance()));
            cacheLineEntity.setDistance(add);
            BigDecimal add1 = transportLinelist1.getCost().add(transportLinelist2.getCost().add(transportLinelist3.getCost()));
            cacheLineEntity.setCost(add1);
            BigDecimal add2 = transportLinelist1.getEstimatedTime().add(transportLinelist2.getEstimatedTime().add(transportLinelist3.getEstimatedTime()));
            cacheLineEntity.setEstimatedTime(add2);
            cacheLineEntity.setTransferCount(2);
            cacheLineEntity.setCreateDate(new Date());
            cacheLineService.save(cacheLineEntity);


             //缓存路线使用表
            CacheLineUseEntity cacheLineUseEntity = new CacheLineUseEntity();
            cacheLineUseEntity.setId(customIdGenerator.nextId(cacheLineUseEntity).toString());
            cacheLineUseEntity.setCacheLineId(s1);
            cacheLineUseEntity.setOrderClassifyId(classifyEntity.getId());
            cacheLineUseEntity.setCreateDate(new Date());
            cacheLineUseService.save(cacheLineUseEntity);




            /**
             * 创建运输任务
             */
            for(int i=orderEntityList1.size()-1;i>=0;i--){

                //判断是否是这一路线的订单
             String str = orderEntityList1.get(i).getCurrentAgencyId()+"#"+ orderEntityList1.get(i).getReceiveAgentId();

                if(!str.equals(classifyEntity.getClassify())){
                    continue;
                }

                //通过订单id 去订单,订单分类表查询改订单数据属于哪一类
                String id = orderEntityList1.get(i).getId();
//                LambdaQueryWrapper<OrderClassifyOrderEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//                lambdaQueryWrapper.eq(OrderClassifyOrderEntity::getOrderId,id);
//                OrderClassifyOrderEntity one = orderClassifyOrderService.getOne(lambdaQueryWrapper);
//
//                //获取到订单分类id 去路线使用表找到该订单使用的缓存线路id
//                LambdaQueryWrapper<CacheLineUseEntity> lineUseEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                lineUseEntityLambdaQueryWrapper.eq(CacheLineUseEntity::getOrderClassifyId,one.getOrderClassifyId());
//                CacheLineUseEntity one1 = cacheLineUseService.getOne(lineUseEntityLambdaQueryWrapper);
//
//                //根据缓存线路id取到线路子表数据
//                LambdaQueryWrapper<CacheLineDetailEntity> lineDetailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                lineDetailEntityLambdaQueryWrapper.eq(CacheLineDetailEntity::getCacheLineId,one1.getCacheLineId());
//                List<CacheLineDetailEntity> CacheLineDetaillist = cacheLineDetailService.list(lineDetailEntityLambdaQueryWrapper);

                //创建运输任务
                //先用订单标号获取运单编号
                String transportbyorderId = transportOrderFeign.getTransportbyorderId(id);

                //存放运输任务数据
                List<TaskTransport> taskTransportList = new ArrayList<>();
                //存放司机作业数据
                List<DriverJob> driverJobList = new ArrayList<>();
                //存放运单与运单任务关联表数据
                List<TransportOrderTask> transportOrderTaskslist = new ArrayList<>();

                //创建运输任务
               for(int j = 0;j<3;j++){
                   TaskTransport taskTransport = new TaskTransport();
                   DriverJob driverJob = new DriverJob();
                   TransportOrderTask transportOrderTask = new TransportOrderTask();
                   String s = customIdGenerator.nextId(taskTransport).toString();
                   taskTransport.setId(s);
                   taskTransport.setTransportTripsId(OrderClassifyAttachlist.get(i).getTripsId());
                   taskTransport.setStartAgencyId(cacheLineDetailEntityList.get(i).getStartAgencyId());
                   taskTransport.setEndAgencyId(cacheLineDetailEntityList.get(i).getEndAgencyId());
                   taskTransport.setTruckId(OrderClassifyAttachlist.get(i).getTruckId());
                   taskTransport.setCreateTime(new Date());

                   //同时创建司机运输任务
                   driverJob.setId(customIdGenerator.nextId(driverJob).toString());
                   driverJob.setTaskTransportId(s);
                   driverJob.setStartAgencyId(cacheLineDetailEntityList.get(i).getStartAgencyId());
                   driverJob.setEndAgencyId(cacheLineDetailEntityList.get(i).getEndAgencyId());
                   driverJob.setDriverId(OrderClassifyAttachlist.get(i).getDriverId());
                   driverJob.setCreateTime(new Date());

                   //最后创建运单与运输任务关联表数据
                   transportOrderTask.setId(customIdGenerator.nextId(transportOrderTask).toString());
                   transportOrderTask.setTransportOrderId(transportbyorderId);
                   transportOrderTask.setTransportTaskId(s);

                   taskTransportList.add(taskTransport);
                   driverJobList.add(driverJob);
                   transportOrderTaskslist.add(transportOrderTask);
               }


                AddShuJuDTO addShuJuDTO = new AddShuJuDTO();
                addShuJuDTO.setTaskTransportList(taskTransportList);
                addShuJuDTO.setDriverJobList(driverJobList);
                addShuJuDTO.setTransportOrderTaskslist(transportOrderTaskslist);


                 //批量添假数据
              boolean piliangadd = taskTransportFeign.piliangadd(addShuJuDTO);

                //TODO 调度完后还要修改 pd_order 订单表 status 为 4已完成 和 运单表 pd_transport_order status为 3 已调度
                orderFeign.updatestatus(id);
                transportOrderFeign.updatestatus(transportbyorderId);


                if (piliangadd){
                   log.info("该订单分类数据已调度完");
                   //将创建运输任务的订单删除
                   orderEntityList1.remove(i);
               }


            }
            }

           return R.ok("ok");
    }
}
